package net.zigin.nhi.waste.view.depotin;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.siberiadante.titlelayoutlib.TitleBarLayout;

import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.adapter.BatchInAdapter;
import net.zigin.nhi.waste.adapter.IActivityUpData;
import net.zigin.nhi.waste.adapter.IAnnounceTypeData;
import net.zigin.nhi.waste.adapter.NoDataAdapter;
import net.zigin.nhi.waste.bean.BatchInBean;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.net.ApiCall;
import net.zigin.nhi.waste.net.BaseResponse;
import net.zigin.nhi.waste.net.HttpRetrofitClient;
import net.zigin.nhi.waste.net.PublicService;
import net.zigin.nhi.waste.utils.StringUtil;
import net.zigin.nhi.waste.view.widget.BatchTypeDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import io.paperdb.Paper;
import io.reactivex.Observable;

/**
 * 批量入库界面
 */
public class BatchInActivity extends AppCompatActivity {

    private TitleBarLayout mTitle;
    private RecyclerView mRv;
    private ImageView mImg;
    private Button mDepot;
    private SmartRefreshLayout mRefresh;

    private BatchInAdapter adapter;
    private NoDataAdapter noDataAdapter = new NoDataAdapter();
    private List<BatchInBean> beanList = new ArrayList<>();
    private boolean isSelected = false;

    private int page = 1;
    private int limit = 10;
    private Set<String> wasteIDs = new HashSet<>();
    private List<String> wasteTypes = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_batch_in);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mRefresh.autoRefresh();
        initData();
    }

    private void initView() {
        ImmersionBar.with(this).init();
        mTitle = findViewById(R.id.title);
        mRefresh = findViewById(R.id.refresh);
        mRv = findViewById(R.id.rv);
        mImg = findViewById(R.id.img);
        mDepot = findViewById(R.id.depot);

        mRv.setLayoutManager(new LinearLayoutManager(this));
    }

    /**
     * 选择类型返回的数据更新adapter
     */
    private IAnnounceTypeData typeDD = new IAnnounceTypeData() {
        @Override
        public void upDataUi(String type) {
            if (StringUtil.isNotEmpty(type)) {
                if (type.equals("all")) {
                    isSelected = true;
                    mImg.setImageResource(R.drawable.depot_in_selected);

                    for (BatchInBean bean : beanList) {
                        bean.setSelect(true);
                    }
                    if (adapter != null) {
                        adapter.notifyData(beanList);
                    }
                } else {
                    if (beanList != null && beanList.size() > 0) {
                        for (BatchInBean batchInBean : beanList) {
                            if (batchInBean.getWasteClassifyCode().equals(type)) {
                                batchInBean.setSelect(true);
                            } else {
                                batchInBean.setSelect(false);
                            }
                        }
                        if (adapter != null) {
                            adapter.notifyData(beanList);
                        }
                    }
                }
            }
        }
    };

    /**
     * 子项取消选中时，全选按钮变更状态为未选中
     */
    private IActivityUpData dd = new IActivityUpData() {
        @Override
        public void upDataUi() {
            isSelected = false;
            mImg.setImageResource(R.drawable.depot_in_unselected);
        }
    };

    /**
     * 获取所有未入库的医废详情，设置全选点击事件
     */
    private void initData() {
        mRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                beanList.clear();
                page = 1;
                Map<String, Object> map1 = new HashMap<>();
                map1.put("collectUserQrCode", Paper.book().read(Constants.COLLECTOR_CODE));
                Observable<BaseResponse<String>> observable1 = HttpRetrofitClient.getInstance().create(PublicService.class)
                        .getPendingInStorageList(Paper.book().read(Constants.TOKEN), map1);
                HttpRetrofitClient.execute(observable1, new ApiCall<String>() {
                    @Override
                    protected void success(String data) {
                        if (StringUtil.isNotEmpty(data)) {
                            Log.i("医废批量入库详情", data);
                            JSONObject object = JSON.parseObject(data);
                            JSONObject collectUser = object.getJSONObject("collectUser");
                            String collectorID = collectUser.getString("id");
                            String collectorName = collectUser.getString("realName");
                            if (collectorID != null) {
                                Paper.book().write(Constants.COLLECTOR_ID, collectorID);
                            }
                            beanList = JSONArray.parseArray(object.getString("wasteBases"), BatchInBean.class);
                            if (beanList != null && beanList.size() > 0 && collectorName != null) {
                                adapter = new BatchInAdapter(beanList, dd, collectorName);
                                mRv.setAdapter(adapter);
                                page++;
                            } else {
                                mRv.setAdapter(noDataAdapter);
                            }
                        } else {
                            mRv.setAdapter(noDataAdapter);
                        }
                        mRefresh.finishRefresh();
                    }

                    @Override
                    public void error(String msg) {
                        super.error(msg);
                        mRefresh.finishRefresh();
                        mRv.setAdapter(noDataAdapter);
                    }
                });
            }
        });

        mRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                Map<String, Object> map1 = new HashMap<>();
                map1.put("collectUserQrCode", Paper.book().read(Constants.COLLECTOR_CODE));
                map1.put("isPage", true);
                map1.put("pageIndex", page);
                map1.put("pageSize", limit);

                Observable<BaseResponse<String>> observable1 = HttpRetrofitClient.getInstance().create(PublicService.class)
                        .getPendingInStorageList(Paper.book().read(Constants.TOKEN), map1);
                HttpRetrofitClient.execute(observable1, new ApiCall<String>() {
                    @Override
                    protected void success(String data) {
                        if (StringUtil.isNotEmpty(data)) {
                            JSONObject object = JSON.parseObject(data);
                            List<BatchInBean> newList = JSONArray.parseArray(object.getString("wasteBases"), BatchInBean.class);
                            if (newList != null && newList.size() > 0) {
                                beanList.addAll(newList);
                                adapter.notifyData(beanList);
                            }
                            if (beanList.size() < limit) {
                                mRefresh.finishLoadMoreWithNoMoreData();
                            } else {
                                mRefresh.finishLoadMore();
                                page++;
                            }
                        } else {
                            mRefresh.finishLoadMoreWithNoMoreData();
                        }
                    }
                });
            }
        });

        mTitle.setRightTextClickListener(v -> {
            BatchTypeDialog dialog = BatchTypeDialog.getInstance(this, BatchInActivity.this, typeDD);
            dialog.show();
        });

        mImg.setOnClickListener(v -> {
            if (isSelected) {
                isSelected = false;
                mImg.setImageResource(R.drawable.depot_in_unselected);

                for (BatchInBean bean : beanList) {
                    bean.setSelect(false);
                }
            } else {
                isSelected = true;
                mImg.setImageResource(R.drawable.depot_in_selected);

                for (BatchInBean bean : beanList) {
                    bean.setSelect(true);
                }
            }
            if (adapter != null) {
                adapter.notifyData(beanList);
            }

        });

        mDepot.setOnClickListener(v -> {
            wasteIDs.clear();
            wasteTypes.clear();
            List<BatchInBean> newList = Paper.book().read(Constants.NEW_BATCH_LIST);
            if (newList != null && newList.size() > 0) {
                for (BatchInBean bean : newList) {
                    if (bean.isSelect()) {
                        wasteIDs.add(bean.getId());
                        wasteTypes.add(bean.getWasteClassifyCode());
                    }
                }
                if (wasteIDs.size() > 0) {
                    if (StringUtil.removeDuplicate(wasteTypes).size() > 1) {
                        Toast.makeText(this, "只能选择同种类型的医废！", Toast.LENGTH_SHORT).show();
                    } else {
                        Paper.book().delete(Constants.NEW_BATCH_LIST);
                        Intent intent = new Intent(BatchInActivity.this, BatchInCheckActivity.class);
                        startActivity(intent);
                        Paper.book().write(Constants.IN_CHECK, wasteIDs);
                    }
                } else {
                    Toast.makeText(this, "请至少选中一项！", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "暂无数据可入库！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BatchTypeDialog.mInstance = null;
    }
}